package com.hongchen.wechat.controller;

import com.hongchen.model.ActGame;
import com.hongchen.model.ActGamePrize;
import com.hongchen.model.ActPrize;
import com.hongchen.model.ActUser;
import com.hongchen.wechat.config.Api;
import com.hongchen.wechat.service.RichService;
import com.jfinal.weixin.sdk.api.ApiResult;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by 张俊 on 2018/1/17 0017.
 */
public class WxCarful extends Api{
    private final RichService richService = enhance(RichService.class);
    static String openId;//定义全局变量的openId
    ActUser actU = new ActUser();//存储用户信息便于使用

    public void index(){
        //这里定义一个对象为了更好的获取用户的个人信息
        ApiResult info = userdetail();
        setSessionAttr("info",info);
        openId=info.get("openid");
        setSessionAttr("openid",openId);
        String nickname=info.get("nickname");
        /**
         * 判断用户刷新以后openid是否为空
         * 如果为空的话重新拉去用户信息
         *
         */
        if(openId==null){
            this.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId() + "&redirect_uri=http://"+chengDong()+".tunnel.echomod.cn/carful&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect");
        }else {

            /**
             *  这里还要查询数据库中是否已经存在这个用户，如果已经存在opneid
             *  如果 存在就直接跳转不存在就说明表用户是新用户存贮用户的信息
             */
            ActUser act=richService.findByOpenid(openId);
            if(act==null){
                //存储用户信息
                ActUser actUser=new ActUser();
                actUser.setCreateTime(new Date());
                actUser.setHeadImg((String) info.get("headimgurl"));
                actUser.setWechatOpenid(openId);
                actUser.setWechatNickname(nickname);
                actUser.setSex((Integer) info.get("sex"));

                actUser.save();
                ActGame actGame=new ActGame();
                actGame.setActUserId(actUser.getId());
                actGame.setSieveChance((long) 5);
                actGame.setNowTime(new Date());
                actGame.save();
            }
            render("game.html");

        }

    }

    public void carfulLevel() {
        String level = getPara("level");
        int le = Integer.parseInt(level);
        Long prize = 0L;//定义用户中的奖品
        ActUser actuser=richService.findByOpenid(openId);
        Long  userId=actuser.getId();
        ActGame actg = richService.finds(userId);//查询用户关联游戏表
        if (actg != null) {
            actg.setNowTime(new Date());
            actg.update();//更新游戏时间
            if (le - 1 <= 1) {
                richService.updateSieveChance(actuser.getId());
            } else if (le - 1 >= 2) {
                List<ActPrize> apList = richService.typePrize(3);//查询奖品集合
                if (apList != null) {
                    ActPrize actPrize = richService.isPrize(apList);//奖品
                    if (actPrize != null) {
                        int stillNum = richService.stillNum(actPrize.getId());//是否还有奖品（是否达到今日奖品领取上限）
                        prize = actPrize.getId();
                        if (stillNum > 0) {
                            richService.updateSieveChanceTwo(actuser.getId());
                            ActGamePrize agp = new ActGamePrize();
                            agp.setGameId(actg.getId());
                            agp.setPrizeId(actPrize.getId());
                            agp.setPrizeNum(richService.lastPrizeNo()); //中奖编号
                            agp.setAwardTime(new Date());//当前中奖时间
                            agp.setAcceptTime(getFetureDate(7));//生成7天后的领奖截止时间
                            agp.setAcceptAddres("河南省郑州市英协路56号传媒创意中心14层河南新维思广告有限公司");
                            if (agp.save()) {//保存中奖信息
                                if (richService.lessOnePrize(actPrize.getId()) >= 1) {//奖品数量减一
                                    setAttr("money", actPrize.getPrizeValue());///奖品价值
                                    setAttr("goods", actPrize.getPrizeName());///奖品名
                                    setAttr("code", agp.getPrizeNum());///奖品编号
                                    setAttr("hasPrize", 1);//奖品
                                }
                            }

                        } else {
                            setAttr("hasPrize", 0);//无奖品
                        }
                    } else {
                        Long[] arrL = new Long[apList.size()];
                        for (int i = 0; i < apList.size(); i++) {
                            arrL[i] = apList.get(i).getId();
                        }
                        prize = arrL[new Random().nextInt(apList.size())];
                        setAttr("hasPrize", 0);//无奖品
                    }
                }
            }renderJson();
        }
    }
    /**
     * 获取未来 第 past 天的日期
     * @param past
     * @return
     */
    public static Date getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        return today;
    }
    public void myPrize() {
        String openid = getSessionAttr("openid");
        //如果session中的openidweinull
        if (openid == null) {
            openid = openId;
        }
        List<ActGamePrize> actGamePrizes = richService.myPrize(openid);
        setAttr("li", actGamePrizes);
        render("myprize.html");
    }

}
